package com.mtzqc.common.loadsir

import com.blankj.utilcode.util.CollectionUtils
import com.kingja.loadsir.callback.Callback
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.mtzqc.common.loadsir.callback.XErrorCallBack
import com.mtzqc.common.loadsir.callback.XLoadingCallBack

interface PageStateView {
    fun showPageSuccess() {
        showPageCallback(SuccessCallback::class.java)
    }

    fun showPageLoading() {
        showPageCallback(stateLoadingClazz())
    }

    fun showPageError() {
        showPageCallback(stateErrorClazz())
    }

    fun <T : Callback> showPageCallback(callback: Class<T>?) {
        callback?.let {
            tryLoadSirService()?.showCallback(it)
        }
    }

    fun stateLoadingClazz(): Class<out Callback>? {
        return XLoadingCallBack::class.java
    }


    fun stateErrorClazz(): Class<out Callback>? {
        return XErrorCallBack::class.java
    }

    fun onRetryBtnClick() {

    }

    fun getSirCallBack(): List<Callback>? {
        return null
    }

    fun addCallback(builder: LoadSir.Builder, clazz: Class<out Callback>?) {
        clazz?.let {
            builder.addCallback(clazz.newInstance())
        }
    }

    fun buildLoadSir(): LoadSir {
        val callbacks = getSirCallBack()
        return if (CollectionUtils.isEmpty(callbacks)) {
            LoadSir.getDefault()
        } else {
            val builder = LoadSir.beginBuilder()
            addCallback(builder, stateErrorClazz())
            addCallback(builder, stateLoadingClazz())
            callbacks!!.forEach {
                builder.addCallback(it)
            }
            builder.build();
        }
    }

    var loadService: LoadService<Any>?

    fun loadSirEnable(): Boolean {
        return true
    }

    fun loadSirTarget(): Any {
        return this
    }

    fun tryLoadSirService(): LoadService<Any>? {
        if (loadSirEnable()) {
            if (null == loadService) {
                loadService = buildLoadSir().register(loadSirTarget()) {
                    onRetryBtnClick()
                }
            }
        }
        return loadService
    }
}